from lxml import etree
import os
import json

file = open('data.json', 'w')
file.write('[')
parser = etree.HTMLParser()

for ind, f in enumerate(os.listdir('cases_html')):

    if ind != 0:
        file.write(',\n')

    # 存储 案件信息的字典
    case_dict = {}

    # 读取 HTML文件
    html = etree.parse(f'./cases_html/{f}', parser=parser)

    # 获取 案件标题
    title = html.xpath("//font[@class='MTitle']/text()")[0]
    case_dict['案件名称'] = title.replace(' ', '')

    # 获取 审判法院
    court = html.xpath("//div[@class='fulltext']/div[@align='center']/text()")[0]
    case_dict['审理法院'] = court

    # 获取 案件编号
    case_flag = html.xpath("//span[@class='case-flag self' or @class='case-flag zero']/text()")[0]
    case_dict['案件编号'] = case_flag

    # 基本结构
    structures = html.xpath("//div[@class='fulltext']/span[@class='anchor-case']/text()")

    # 主要内容
    for i in range(len(structures) - 1):
        content = html.xpath(
            f"//div[@class='fulltext']/span[@class='anchor-case'][text()='{structures[i]}']//following::text()[position()<count(//span[@class='anchor-case'][text()='{structures[i]}']//following::text())-count(//span[@class='anchor-case'][text()='{structures[i + 1]}']//following::text())]")

        case_dict[structures[i]] = ''.join(content).replace('\u3000', '')

    # 落款
    end = html.xpath("//div[@align='right']/text()")
    case_dict['落款'] = [e.replace('\u3000', '').replace(' ', '').replace('\xa0', '') for e in end]

    laws = html.xpath("//h4[@name='本案法律依据']//following::div[@class='block'][1]/ul/li/a[@target='_blank']/text()")
    case_dict['法律依据'] = list(
        filter(None, [law.replace(' ', '').replace('\n', '').replace('\r', '') for law in laws]))

    # print(case_dict,'\n\n\n\n')
    json.dump(case_dict, file, ensure_ascii=False)


file.write(']')
file.close()